﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using AspNetCoreTest.Data;
using AspNetCoreTest.Models;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace AspNetCoreTest.Pages.Movies
{
    public class IndexModel : PageModel
    {
        private readonly AspNetCoreTest.Data.AspNetCoreTestContext _context;

        public IndexModel(AspNetCoreTest.Data.AspNetCoreTestContext context)
        {
            _context = context;
        }

        public IList<Movie> Movie { get; set; }

        [BindProperty(SupportsGet = true)]
        public string SearchString { get; set; }

        public SelectList Genres { get; set; }

        [BindProperty(SupportsGet = true)]
        public string MovieGenre { get; set; }

        public async Task OnGetAsync()
        {
            IQueryable<string> genreQuery = from m in _context.Movie
                                            orderby m.Genre
                                            select m.Genre;
            Genres = new SelectList(await genreQuery.Distinct().ToListAsync());

            var movies = from m in _context.Movie select m;
            if (!string.IsNullOrEmpty(SearchString))
            {
                movies = movies.Where(p => p.Title.Contains(SearchString));
            }
            if (!string.IsNullOrEmpty(MovieGenre))
            {
                movies = movies.Where(x => x.Genre == MovieGenre);
            }
            Movie = await movies.ToListAsync();
            Rem();
        }

        private void Rem()
        {
            List<Movie> list = new List<Movie>();
            list.Add(null);
            list.Add(new Movie() { ID = 2 });
            list.Add(new Movie() { ID = 3 });
            list.Add(null);
            list.Add(null);
            list.Add(new Movie() { ID = 4 });
            list.Add(new Movie() { ID = 5 });
            list.Add(null);

            int count = list.Count;
            for (int i = 0; i < count; i++)
            {
                if (list[i] == null)
                {
                    int newCount = i++;
                    for (; i < count; i++)
                    {
                        if (list[i] != null) list[newCount++] = list[i];
                    }
                    list.RemoveRange(newCount, count - newCount);
                    break;
                }
            }
        }
    }
}
